package org.fungene.services.david;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

public class DavidLauncher {

	public DavidModule module;

	public DavidLauncher() {
		super();
	}

	public DavidLauncher(String type, String annot, String ids, String tool) {
		super();
		this.module = new DavidModule(type, annot, ids, tool);
	}

	public JSONObject launch() {
		try {

			// Get basic info from server
			System.out.println(this.module.getRequestURL());
			HttpClient httpClient = new HttpClient();
			GetMethod get = new GetMethod(this.module.getRequestURL());
			httpClient.executeMethod(get);
			String levelOne = get.getResponseBodyAsString();
			get.releaseConnection();
			System.err.println("Level 1 is finished!");

			NameValuePair[] nameValue = new NameValuePair[2];
			// Get value of 'rowids'
			String regex = "rowids.value\\s*=\\s*\"(.*)\"";
			Pattern pattern = Pattern.compile(regex);
			Matcher matcher = pattern.matcher(levelOne);
			if (matcher.find()) {
				nameValue[0] = new NameValuePair("rowids", matcher.group(1));
			}
			// Get value of 'annot'
			regex = "annot.value\\s*=\\s*\"(.*)\"";
			pattern = Pattern.compile(regex);
			matcher = pattern.matcher(levelOne);
			if (matcher.find()) {
				nameValue[1] = new NameValuePair("annot", matcher.group(1));
			}
			// Get target page
			regex = "action\\s*=\\s*\"(.*)\"";
			pattern = Pattern.compile(regex);
			matcher = pattern.matcher(levelOne);
			String URL = "http://david.abcc.ncifcrf.gov/";
			if (matcher.find()) {
				URL += matcher.group(1);
			}

			// Post form to the server
			PostMethod post = new PostMethod(URL);
			post.setRequestBody(nameValue);

			String levelTwo = "";
			try {
				httpClient.executeMethod(post);
				levelTwo = post.getResponseBodyAsString();
			} catch (HttpException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			post.releaseConnection();
			System.err.println("Level 2 is finished!");

			// Download file and parse it
			regex = "UserDownload/(.*\\.txt)";
			pattern = Pattern.compile(regex);
			matcher = pattern.matcher(levelTwo);
			URL = "http://david.abcc.ncifcrf.gov/";
			if (matcher.find()) {
				URL += matcher.group(0);
			}

			get = new GetMethod(URL);
			httpClient.executeMethod(get);
			String levelThree = get.getResponseBodyAsString();
			get.releaseConnection();
			System.err.println("Level 3 is finished!");
//			System.out.println(levelThree);

			return getResults(levelThree);
		} catch (IOException e) {
			return null;
		}
	}

	private JSONObject getResults(String resultString) {
		String[] pair = resultString.split("\n");
		// System.out.println(pair.length);
		JSONObject ret = new JSONObject();
		JSONObject result = new JSONObject();
		for (String line : pair) {
			int pos = line.indexOf("\t");
			String name = "";
			String value = "";
			if (pos != -1) {
				name = line.substring(0, pos);
				value = line.substring(pos + 1);
			}
			result.clear();
			result.put("name", name);
			result.put("value", value);
			ret.accumulate("result", result);
		}
		return ret;
	}
}
